package com.github.ecbp.common.utils;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import com.github.ecbp.common.resp.CaptchaVO;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;

/**
 * 生成图片验证码
 */
public class CaptchaUtils {

    public static CaptchaVO getImage(OutputStream out) {
        CaptchaVO captchaVO = new CaptchaVO();
        AbstractCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 6);
        captcha.write(out);
        captchaVO.setCode(captcha.getCode());
        return captchaVO;
    }

    public static CaptchaVO getImageNew(OutputStream out) {
        CaptchaVO captchaVO = new CaptchaVO();

        // png类型
        //        Captcha captcha = new SpecCaptcha(200 100);

        //        // gif类型
        Captcha captcha = new GifCaptcha(200, 100, 4);

        //        // 中文类型
        //        Captcha captcha = new ChineseCaptcha(200, 100, 4);

        //        // 中文gif类型
        //        Captcha captcha = new ChineseGifCaptcha(200, 100, 4);

        //        // 算术类型
        //        Captcha captcha = new ArithmeticCaptcha(200 100);
        //        captcha.setLen(3);  // 几位数运算，默认是两位
        //        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        //        captcha.text();  // 获取运算的结果：5

        try {
            captcha.setFont(Captcha.FONT_1, 65);
        } catch (IOException | FontFormatException e) {
            e.printStackTrace();
        }
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        captcha.out(out);

        captchaVO.setCode(captcha.text());
        return captchaVO;
    }

    public static void main(String[] args) {
        // 测试重复
        Set<String> result = new HashSet<>(600);
        for(int i=0; i< 500; i++){
            result.add(getImageNew(new ByteArrayOutputStream()).getCode());
        }
        System.out.println(result.size());
    }
}
